﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            departmentUserPermission: true, // 能进到本页面，就是true
            departmentUserAddPermission: false,
            departmentUserRemovePermission: false,
            createDepartUserPermission: false,
            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            createDialogVisible: false, // 创建用户对话框，是否显示
            addCurrentDialogVisible: false,// 将现有用户添加到科室
            tableData: [],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            treeData: [],
            depCurrentPage: 1,
            depUserTotalCount: 0,
            depPageSize: 10,
            depUserTotal: 0,
            depSelectedUsers: [],


            // 添加现有对话框
            systemUsers: [],
            filterSystemUserName: '',
            systemUserTotal: 0,
            systemPageSize: 10,
            systemCurrentPage: 1,
            systemSelectedUsers: [],


            user: {
                userName: null,
                name: null,
                passwordHash: 'YA123456',
                email: null,
                phoneNumber: null,
                outerNumber: null,
                idCardNumber: null,
                jobNumber: null,
                isActive: true,
                lockoutEnabled: true,
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                userName: [
                    { required:true,message:'请输入用户名',trigger:'blur'}
                ],
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入用户编号', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入外部编号', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message:'请输入正确格式邮箱地址',trigger:'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            }
        },
        methods: {

            onOuterCodeChange(val) {
                const vm = this;
                vm.user.code = val;
            },

            depSearch() {
                var vm = this;
                vm.depCurrentPage = 1;
                vm.loadDepUsers();
            },

            // 科室用户当前页改变
            depCurrentPageChange(val) {
                var vm = this;
                vm.depCurrentPage = val;
                vm.loadDepUsers(vm.department.id);
            },

            // 科室用户，每页数量改变
            depPageSizeChange(val) {
                var vm = this;
                vm.depPageSize = val;
                vm.depCurrentPage = 1;
                vm.loadDepUsers(vm.department.id);
            },

            // 科室选中用户改变
            depUserSelectionChange(val) {
                var vm = this;
                vm.depSelectedUsers = val;
            },

            // 加载当前科室下用户
            loadTableData() {
                var vm = this;
                if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                    vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                    vm.loadDepUsers(vm.department.id);
                }
                else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                    // 提示系统还没有任何科
                }
                else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                    // 根据登录科室加载用户
                    vm.loadDepUsers(vm.department.id);
                }
            },

            loadDepUsers(id) {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/department-user/get-list?id=${vm.department.id}&filterName=${vm.filterName}&page=${vm.depCurrentPage}&pageSize=${vm.depPageSize}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data;
                    }
                });
            },

            systemSearch() {
                var vm = this;
                vm.systemCurrentPage = 1;
                vm.loadSystemUsers();
            },

            // 系统用户列表，每页数量改变
            stytemPageSizeChange(val) {
                var vm = this;
                vm.systemPageSize = val;
                vm.systemCurrentPage = 1;
                vm.loadSystemUsers();
            },

            // 系统用户列表，当前页改变
            stytemCurrentPageChange(val) {
                var vm = this;
                vm.systemCurrentPage = val;
                vm.loadSystemUsers();
            },


            // 选中的系统用户改变
            systemSelectedChange(val) {
                var vm = this;
                vm.systemSelectedUsers = val;
            },

            loadSystemUsers() {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/department-user/get-users-for-add?depId=${vm.department.id}&filterName=${vm.filterSystemUserName}&page=${vm.systemCurrentPage}&pageSize=${vm.systemPageSize}`
                }).then((res) => {
                    if (res.code == 0) {
                        vm.systemUsers = res.data.users;
                        vm.systemUserTotal = res.data.totalCount;
                    }
                });
            },

            // 打开创建用户窗口
            showCreate() {
                var vm = this;
                vm.createDialogVisible = true;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['creatUserForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/epartment-user/create-user-for-department?depId=${vm.department.id}`,
                            data: JSON.stringify(vm.user)
                        }).then(res => {
                            if (res.code == 0) {
                                vm.resetCreateForm();
                                vm.loadDepUsers();
                                abp.notify.success(res.msg);
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        })
                    }
                });

            },


            // 保存用户
            saveUserToDeparment() {
                var vm = this;
                abp.ajax({
                    type: "POST",
                    url: `/api/epartment-user/create-user-for-department?depId=${vm.department.id}`,
                    data: JSON.stringify(vm.user)
                }).then((res) => {
                    if (res.code = 0) {
                        abp.notify.success(res.msg);
                    }
                    else {
                        abp.message.error(res.msg);
                    }
                })
            },

            // 打开添加现有用户窗口
            showAdd() {
                var vm = this;
                vm.addCurrentDialogVisible = true;
                vm.loadSystemUsers();
            },

            // 关闭添加对话框时
            closeAddDialog() {
                var vm = this;
                vm.filterSystemUserName = '';
                vm.addCurrentDialogVisible = false;
                vm.systemUserTotal = 0;
                vm.systemCurrentPage = 1;
                vm.systemSelectedUsers = [];
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-tree-data"
                        }).then((res) => {
                            if (res.code === 0) {
                                vm.treeData = res.data;
                                resolve();
                            }
                        });
                    }
                    else if (!vm.multiDepartmentPermission) { // 科室用户
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }

                });
            },

            // 向科室添加用户   
            addUserToDepartment() {
                var vm = this;
                if (vm.systemSelectedUsers.length > 0) {
                    var idList = vm.systemSelectedUsers.map((item) => item.id);
                    abp.ajax({
                        type: 'POST',
                        url: `/api/epartment-user/add-current-user-to-department?depId=${vm.department.id}`,
                        data: JSON.stringify(idList)
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.closeAddDialog();
                            vm.loadDepUsers(vm.department.id);
                        }
                    });
                }
                else {
                    abp.notify.error('无选中用户，请先选择用户。')
                }
            },

            // 将当前用户从当前科室中移除
            removeUser() {
                var vm = this;
                if (vm.depSelectedUsers.length > 0) {
                    abp.message.confirm('选中的用户将会从当前科室移除。')
                        .then(confirmed => {
                            if (confirmed) {
                                var idList = vm.depSelectedUsers.map(item => item.id);
                                abp.ajax({
                                    type: 'POST',
                                    url: `/api/department-user/remove-users?depId=${vm.department.id}`,
                                    data: JSON.stringify(idList)
                                }).then((res) => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.loadDepUsers();
                                    }
                                });
                            }
                        });
                }
                else {
                    abp.notify.error("请选中要移除的用户。");
                }
            },

            // 加载当前用户角色和权限.
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('BaseSettingGroup.DeparmentUsers')) { // 科室用户页面权限
                        vm.departmentUserPermission = true;
                        if (abp.auth.isGranted('BaseSettingGroup.DeparmentUsers.Add')) {// 添加现有用户权限
                            vm.departmentUserAddPermission = true;
                        }

                        if (abp.auth.isGranted('BaseSettingGroup.DeparmentUsers.Remove')) { // 移除科室用户权限
                            vm.departmentUserRemovePermission = true;
                        }

                        if (abp.auth.isGranted('BaseSettingGroup.DeparmentUsers.CreateDepartmentUser')) { // 创建科室用户权限
                            vm.createDepartUserPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) {
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击科室
            nodeClicked(node) {
                if (node.icon != 'fa fa-hospital') {
                    var vm = this;
                    vm.department = node;
                    vm.loadDepUsers(vm.department.id);
                }
            },

            // 创建科室用用户，表单重置
            resetCreateForm() {
                var vm = this;
                vm.$refs['creatUserForm'].resetFields();
                vm.createDialogVisible = false;
            },

            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadTreeData().then(() => {
                            vm.loadTableData();
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});